package com.nwpu.intimacy.user;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.model.CityModel;
import com.nwpu.intimacy.model.DistrictModel;
import com.nwpu.intimacy.model.ProvinceModel;
import com.nwpu.intimacy.service.XmlParserHandler;
import com.nwpu.intimacy.utils.CacheUtil;
import com.nwpu.intimacy.wheel.widget.OnWheelChangedListener;
import com.nwpu.intimacy.wheel.widget.WheelView;
import com.nwpu.intimacy.wheel.widget.adapters.ArrayWheelAdapter;

public class HometownModifyDialog extends Dialog implements
		OnWheelChangedListener {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/modify";

	/**
	 * 所有省
	 */
	protected String[] mProvinceDatas;
	/**
	 * key - 省 value - 市
	 */
	protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
	/**
	 * key - 市 values - 区
	 */
	protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

	/**
	 * key - 区 values - 邮编
	 */
	protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

	/**
	 * 当前省的名称
	 */
	protected String mCurrentProviceName;
	/**
	 * 当前市的名称
	 */
	protected String mCurrentCityName;
	/**
	 * 当前区的名称
	 */
	protected String mCurrentDistrictName = "";

	/**
	 * 当前区的邮政编码
	 */
	protected String mCurrentZipCode = "";

	private Context context;

	private WheelView mViewProvince;
	private WheelView mViewCity;

	private Button mBtnConfirm;
	private Button mBtnCancel;

	private SharedPreferences sp_userMessage;

	private final static int USER_MODIFY_FAIL = 0x115;
	private final static int USER_MODIFY_AREA_SUCCESS = 0x116;

	private Handler modifyHandler;

	public HometownModifyDialog(Context context, boolean cancelable,
			OnCancelListener cancelListener) {

		super(context, cancelable, cancelListener);

	}

	public HometownModifyDialog(Context context) {

		super(context);
		this.context = context;

	}

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.modify_privation_dialog);

		sp_userMessage = context.getSharedPreferences("userMessage",
				Context.MODE_PRIVATE);

		setUpViews();
		setUpListener();
		setUpData();

		mBtnConfirm.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				modifyHometown();

			}
		});

		// 线程交互
		modifyHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_MODIFY_AREA_SUCCESS: {

					Toast.makeText(context, "地区修改成功!", Toast.LENGTH_SHORT)
							.show();

					break;

				}
				case USER_MODIFY_FAIL: {

					Toast.makeText(context, "修改错误!", Toast.LENGTH_SHORT).show();

				}
				default:
					super.handleMessage(msg);
				}
			}

		};

	}

	private void setUpViews() {

		mViewProvince = (WheelView) findViewById(R.id.id_province);
		mViewCity = (WheelView) findViewById(R.id.id_city);
		mBtnConfirm = (Button) findViewById(R.id.modify_ok_button_dialog);
		mBtnCancel = (Button) findViewById(R.id.modify_cancel_button_dialog);

	}

	private void setUpListener() {

		// 添加change事件
		mViewProvince.addChangingListener(this);
		// 添加change事件
		mViewCity.addChangingListener(this);

	}

	private void setUpData() {
		initProvinceDatas();
		mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(context,
				mProvinceDatas));
		// 设置可见条目数量
		mViewProvince.setVisibleItems(7);
		mViewCity.setVisibleItems(7);
		updateCities();
		updateAreas();
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {

		if (wheel == mViewProvince) {
			updateCities();
		} else if (wheel == mViewCity) {
			updateAreas();
		}

	}

	/**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity
				.setViewAdapter(new ArrayWheelAdapter<String>(context, cities));
		mViewCity.setCurrentItem(0);
		updateAreas();
	}

	/**
	 * 解析省市区的XML数据
	 */

	protected void initProvinceDatas() {
		List<ProvinceModel> provinceList = null;
		AssetManager asset = context.getAssets();
		try {
			InputStream input = asset.open("province_data.xml");
			// 创建一个解析xml的工厂对象
			SAXParserFactory spf = SAXParserFactory.newInstance();
			// 解析xml
			SAXParser parser = spf.newSAXParser();
			XmlParserHandler handler = new XmlParserHandler();
			parser.parse(input, handler);
			input.close();
			// 获取解析出来的数据
			provinceList = handler.getDataList();
			// */ 初始化默认选中的省、市、区
			if (provinceList != null && !provinceList.isEmpty()) {
				mCurrentProviceName = provinceList.get(0).getName();
				List<CityModel> cityList = provinceList.get(0).getCityList();
				if (cityList != null && !cityList.isEmpty()) {
					mCurrentCityName = cityList.get(0).getName();
					List<DistrictModel> districtList = cityList.get(0)
							.getDistrictList();
					mCurrentDistrictName = districtList.get(0).getName();
					mCurrentZipCode = districtList.get(0).getZipcode();
				}
			}
			// */
			mProvinceDatas = new String[provinceList.size()];
			for (int i = 0; i < provinceList.size(); i++) {
				// 遍历所有省的数据
				mProvinceDatas[i] = provinceList.get(i).getName();
				List<CityModel> cityList = provinceList.get(i).getCityList();
				String[] cityNames = new String[cityList.size()];
				for (int j = 0; j < cityList.size(); j++) {
					// 遍历省下面的所有市的数据
					cityNames[j] = cityList.get(j).getName();
					List<DistrictModel> districtList = cityList.get(j)
							.getDistrictList();
					String[] distrinctNameArray = new String[districtList
							.size()];
					DistrictModel[] distrinctArray = new DistrictModel[districtList
							.size()];
					for (int k = 0; k < districtList.size(); k++) {
						// 遍历市下面所有区/县的数据
						DistrictModel districtModel = new DistrictModel(
								districtList.get(k).getName(), districtList
										.get(k).getZipcode());
						// 区/县对于的邮编，保存到mZipcodeDatasMap
						mZipcodeDatasMap.put(districtList.get(k).getName(),
								districtList.get(k).getZipcode());
						distrinctArray[k] = districtModel;
						distrinctNameArray[k] = districtModel.getName();
					}
					// 市-区/县的数据，保存到mDistrictDatasMap
					mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
				}
				// 省-市的数据，保存到mCitisDatasMap
				mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {

		}
	}

	public void modifyHometown() {

		new Thread() {

			public void run() {

				try {

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					Bitmap photo = CacheUtil.GetFromFile(
							sp_userMessage.getString("USER_NAME", ""), "Photo");

					jsonObject.put("username",
							sp_userMessage.getString("USER_NAME", ""));
					jsonObject.put("password",
							sp_userMessage.getString("PASSWORD", ""));
					jsonObject.put("portrait", bitmaptoString(photo));

					jsonObject.put("sex", sp_userMessage.getInt("SEX", 0));
					jsonObject.put("comment",
							sp_userMessage.getString("COMMENT", ""));
					jsonObject.put("area", mCurrentProviceName + ";"
							+ mCurrentCityName);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair("modify",
							jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					/*
					 * String result = new String(
					 * EntityUtils.toString(httpResponse.getEntity()),
					 * HTTP.UTF_8);
					 */

					Log.e("result", result);
					Log.e("hkq", URLDecoder.decode(result, HTTP.UTF_8));
					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("result").equals("success")) {

						sp_userMessage.edit()
								.putString("AREA", mCurrentCityName).commit();
						Message msg = new Message();
						msg.what = USER_MODIFY_AREA_SUCCESS;
						msg.obj = result;
						modifyHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_MODIFY_FAIL;
						msg.obj = result;
						modifyHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}

	/**
	 * 将Bitmap格式图片转化为字符串
	 * 
	 * @param bitmap
	 * @return
	 */
	public String bitmaptoString(Bitmap bitmap) {

		// 将Bitmap转换成字符串
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}

}
